package com.zhp.web;

import com.alibaba.druid.util.StringUtils;
import com.zhp.pojo.HUser;
import com.zhp.service.UserService;
import com.zhp.service.impl.UserServiceImpl;
import com.zhp.utils.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @date 2023/4/11
 * @desc  处理登录请求
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String uname = req.getParameter("uname");
        //接的是明文密码
        String upwd = req.getParameter("upwd");
        String remember = req.getParameter("remember");

        HUser hUser = new HUser();
        hUser.setUname(uname);
        //把明文密码 改为密文
        String pwd = MD5Util.EncoderPwdByMd5(upwd);
        hUser.setUpwd(pwd);

        UserService userService = new UserServiceImpl();

        HUser result = userService.login(hUser);

        if(result!=null){

            //登录成功  判断用户是否勾选了记住我
            if(!StringUtils.isEmpty(remember)){
                //发送cookie
                Cookie cookie = new Cookie("remember", uname + "-" + upwd);
                // 设置cookie的有效期
                cookie.setMaxAge(Integer.parseInt(remember));

                resp.addCookie(cookie);
            }

            HttpSession session = req.getSession();
            //登陆成功 把用户信息放在session
            session.setAttribute("u",result);
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }else{

            req.setAttribute("login_info","用户名或密码错误");
            //失败 跳转到登录页面
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }

    }
}
